<template>
  <div class="audio" :style="style">
    <div class="audio-container">
      <div class="audio-info">
        <div class="audio-title">{{ name || '音频文件' }}</div>
        <div class="audio-controls">
          <el-button
            :icon="isPlaying ? VideoPause : VideoPlay"
            circle
            size="large"
            type="primary"
            style="font-size: 20px;"
            @click="togglePlay"
          />
        </div>
      </div>
      <div class="audio-progress">
        <el-slider
          v-model="progress"
          :max="duration"
          :show-tooltip="false"
          @change="onProgressChange"
        />
      </div>
      <div class="audio-time">
        <span>{{ formatTime(currentTime) }}</span>
        <span>{{ formatTime(duration) }}</span>
      </div>
    </div>
    <audio
      ref="audioRef"
      :src="url"
      preload="metadata"
      @loadedmetadata="onLoadedMetadata"
      @timeupdate="onTimeUpdate"
      @ended="onEnded"
    />
  </div>
</template>

<script setup>
import { VideoPlay, VideoPause } from '@element-plus/icons-vue'

const { url, name, visible } = defineProps({
  /** @name 音频文件地址 */
  url: {
    type: String,
    required: true
  },
  /** @name 音频文件名称 */
  name: {
    type: String,
    default: ''
  },
  /** @name 是否可见 */
  visible: {
    type: Boolean,
    default: false
  }
})

const audioRef = ref(null)
const isPlaying = ref(false)
const currentTime = ref(0)
const duration = ref(0)
const progress = ref(0)

const style = ref({
  width: '320px',
  height: '140px'
})

/**
 * @name 切换播放状态
 */
function togglePlay() {
  if (!audioRef.value) return
  
  if (isPlaying.value) {
    audioRef.value.pause()
  } else {
    audioRef.value.play()
  }
}

/**
 * @name 音频元数据加载完成
 */
function onLoadedMetadata() {
  if (audioRef.value) {
    duration.value = audioRef.value.duration || 0
  }
}

/**
 * @name 音频时间更新
 */
function onTimeUpdate() {
  if (audioRef.value) {
    currentTime.value = audioRef.value.currentTime
    progress.value = currentTime.value
  }
}

/**
 * @name 音频播放结束
 */
function onEnded() {
  isPlaying.value = false
  currentTime.value = 0
  progress.value = 0
}

/**
 * @name 进度条改变
 */
function onProgressChange(value) {
  if (audioRef.value) {
    audioRef.value.currentTime = value
    currentTime.value = value
  }
}

/**
 * @name 格式化时间
 * @param {number} time 时间（秒）
 */
function formatTime(time) {
  if (!time || isNaN(time)) return '00:00'
  
  const minutes = Math.floor(time / 60)
  const seconds = Math.floor(time % 60)
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

// 监听音频播放状态
watch(() => audioRef.value, (audio) => {
  if (audio) {
    audio.addEventListener('play', () => {
      isPlaying.value = true
    })
    audio.addEventListener('pause', () => {
      isPlaying.value = false
    })
  }
})

// 监听可见性变化
watch(() => visible, (value) => {
  if (!value && audioRef.value && isPlaying.value) {
    audioRef.value.pause()
  }
})

// 暴露方法给父组件
defineExpose({
  play: () => audioRef.value?.play(),
  pause: () => audioRef.value?.pause(),
  togglePlay
})
</script>

<style lang="scss" scoped>
.audio {
  padding: 16px;
  
  .audio-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
  
  .audio-info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
    
    .audio-title {
      font-size: 14px;
      font-weight: 500;
      color: #c7c7c7;
      flex: 1;
      margin-right: 12px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .audio-controls {
      flex-shrink: 0;
    }
  }
  
  .audio-progress {
    margin-bottom: 8px;
    
    :deep(.el-slider__runway) {
      height: 4px;
    }
    
    :deep(.el-slider__button) {
      width: 12px;
      height: 12px;
    }
  }
  
  .audio-time {
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    color: #666;
  }
}
</style>